import React, { useState, useEffect, useMemo } from 'react';
import {
  Table,
  Card,
  PaginationProps,
  Button,
  Space,
  Typography,
  Tag,
  Modal,
  Tree,
  Grid,
  Spin,
} from '@arco-design/web-react';
import type { TableColumnProps } from '@arco-design/web-react';
import PermissionWrapper from '@/components/PermissionWrapper';
import {
  IconDelete,
  IconDownload,
  IconEdit,
  IconPlus,
  IconUpload,
} from '@arco-design/web-react/icon';
import styles from './style/index.module.less';
import './mock';
import { useActivate, useAliveController } from 'react-activation';
import { useHistory } from 'react-router-dom';
import Api from '@/services/api';
import { DetailModal } from './detailModal';
import * as Model from '@/services/model';
import { TreeDataType } from '@arco-design/web-react/es/Tree/interface';

const { Row, Col } = Grid;
const generateTreeData = (list) => {
  return list.map((e) => {
    const children = Array.isArray(e.children)
      ? generateTreeData(e.children)
      : null;
    return { ...e, key: e.id, title: e.name, children };
  });
};

const loopTreeData = (data, key, callback) => {
  data.some((item, index, arr) => {
    if (item.key === key) {
      callback(item, index, arr);
      return true;
    }

    if (item.children) {
      return loopTreeData(item.children, key, callback);
    }
  });
};

function SearchTable() {
  const history = useHistory();

  const [data, setData] = useState<TreeDataType[]>([]);

  const [loading, setLoading] = useState(true);
  const [formParams, setFormParams] = useState({});

  const [selectedOrgnizes, setSelectedOrgnizes] = useState<Model.Orgnize[]>([]);
  const [orgnizeDetail, setOrgnizeDetail] = useState<Model.Orgnize | false>(
    false
  );
  const [orgnizeDetailPromise, setOrgnizeDetailPromise] =
    useState<(params: Model.Orgnize) => void>();
  const [expandedKeys, setExpandedKeys] = useState<string[]>(['']);
  const aliveController = useAliveController();
  useActivate(() => {
    console.log('active');
  });
  useEffect(() => {
    fetchData();
  }, [JSON.stringify(formParams)]);

  const fetchData = () => {
    setLoading(true);
    Api.orgnizeList({
      ...formParams,
    })
      .then((res) => {
        setData(generateTreeData(res.list));

        setLoading(false);
      })
      .catch(() => {
        setLoading(false);
      });
  };

  const handleDelete = (docks: Model.Orgnize[]) => {
    Modal.confirm({
      title: '确定删除以下组织吗？',
      content: (
        <div>
          <Typography.Text type="secondary">
            {docks.map((e) => e.name).join('，')}
          </Typography.Text>
        </div>
      ),
      onOk: () => {
        Api.deleteDocks(docks.map((e) => e.id)).then(() => {
          fetchData();
        });
      },
    });
  };

  const columns: TableColumnProps[] = [
    { title: '组织名称', dataIndex: 'name' },
    {
      title: '操作',
      render: (col, item) => {
        return (
          <Space>
            <Button
              size="small"
              type="primary"
              onClick={() => setOrgnizeDetail(item)}
            >
              编辑
            </Button>

            <Button
              size="small"
              type="primary"
              status="danger"
              onClick={() => handleDelete([item])}
            >
              删除
            </Button>
          </Space>
        );
      },
    },
  ];

  return (
    <Card>
      <div className={styles['button-group']}>
        <Space>
          <Button
            onClick={() => {
              setOrgnizeDetail(new Model.Orgnize());
              setOrgnizeDetailPromise(() => (params: Model.Orgnize) => {
                data.push({
                  title: params.name,
                });
                setData([...data]);
              });
            }}
            type="primary"
            icon={<IconPlus />}
          >
            新增组织
          </Button>
          <Button
            onClick={() => handleDelete(selectedOrgnizes)}
            type="primary"
            status="danger"
            disabled={selectedOrgnizes.length <= 0}
            icon={<IconDelete />}
          >
            删除组织
          </Button>
        </Space>
      </div>
      <Row>
        <Col span={8}>
          {loading ? (
            <Spin />
          ) : (
            <Tree
              draggable
              checkable
              blockNode
              expandedKeys={expandedKeys}
              onExpand={(e) => setExpandedKeys(e)}
              renderExtra={(node) => {
                return (
                  <Space size={0} style={{ marginTop: 4 }}>
                    <Button
                      type="text"
                      size="mini"
                      onClick={() => {
                        setOrgnizeDetail({
                          id: node.dataRef.key,
                          name: node.dataRef.title as string,
                        });
                        setOrgnizeDetailPromise(
                          () => (params: Model.Orgnize) => {
                            loopTreeData(
                              data,
                              node.dataRef.key,
                              (item, index, arr) => {
                                item.title = params.name;

                                setData([...data]);
                              }
                            );
                          }
                        );
                      }}
                    >
                      <IconEdit
                        style={{
                          color: '#3370ff',
                        }}
                      />
                    </Button>
                    <Button
                      type="text"
                      size="mini"
                      onClick={() => {
                        setOrgnizeDetail(new Model.Orgnize());
                        setOrgnizeDetailPromise(
                          () => (params: Model.Orgnize) => {
                            const dataChildren = node.dataRef.children || [];
                            dataChildren.push({
                              title: params.name,
                              key: Date.now().toString(),
                            });
                            node.dataRef.children = dataChildren;
                            setData([...data]);
                            if (!expandedKeys.includes(node.dataRef.key)) {
                              setExpandedKeys([
                                ...expandedKeys,
                                node.dataRef.key,
                              ]);
                            }
                          }
                        );
                      }}
                    >
                      <IconPlus
                        style={{
                          color: '#3370ff',
                        }}
                      />
                    </Button>
                    <Button
                      type="text"
                      size="mini"
                      onClick={() => {
                        Modal.confirm({
                          title: '确定删除以下组织吗？',
                          content: (
                            <div>
                              <Typography.Text type="secondary">
                                {node.dataRef.title}
                              </Typography.Text>
                            </div>
                          ),
                          onOk: () => {
                            loopTreeData(
                              data,
                              node.dataRef.key,
                              (item, index, arr) => {
                                arr.splice(index, 1);
                              }
                            );
                            setData([...data]);
                          },
                        });
                      }}
                    >
                      <IconDelete
                        style={{
                          fontSize: 12,
                          color: '#3370ff',
                        }}
                      />
                    </Button>
                  </Space>
                );
              }}
              onDrop={({ dragNode, dropNode, dropPosition }) => {
                let dragItem;
                loopTreeData(data, dragNode.props._key, (item, index, arr) => {
                  arr.splice(index, 1);
                  dragItem = item;
                  dragItem.className = 'tree-node-dropover';
                });

                if (dropPosition === 0) {
                  loopTreeData(
                    data,
                    dropNode.props._key,
                    (item, index, arr) => {
                      item.children = item.children || [];
                      item.children.push(dragItem);
                    }
                  );
                } else {
                  loopTreeData(
                    data,
                    dropNode.props._key,
                    (item, index, arr) => {
                      arr.splice(
                        dropPosition < 0 ? index : index + 1,
                        0,
                        dragItem
                      );
                    }
                  );
                }

                setData([...data]);
                setTimeout(() => {
                  dragItem.className = '';
                  setData([...data]);
                }, 1000);
              }}
              treeData={data}
            ></Tree>
          )}
        </Col>
      </Row>

      <DetailModal
        onCancel={() => setOrgnizeDetail(false)}
        onOk={(params) => {
          setOrgnizeDetail(false);
          orgnizeDetailPromise(params);
        }}
        orgnizeInfo={orgnizeDetail}
      />
    </Card>
  );
}

export default SearchTable;
